package com.vshop.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * json方式http的post请求方法
 *
 * @author lm
 * @date 2020/10/19 15:54
 */
@Slf4j
public class HttpUtil {
    /**
     * post请求
     *
     * @param url
     * @param param
     * @return
     */
    public static String httpPost(String url, String param) {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(180000)
                .setConnectionRequestTimeout(180000)
                .setSocketTimeout(180000)
                .build();

        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("x-access-token", "xAccessToken");
        StringEntity entity = null;

        if (param != null) {
            entity = new StringEntity(param, "UTF-8");
        }

        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        String returnStr = "";
        try {
            response = httpClient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            if (status.getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity httpEntity = response.getEntity();
                returnStr = EntityUtils.toString(httpEntity, "UTF-8");
                //返回具体的实体
            } else {
                log.info("Http请求握手失败:" + status.getStatusCode());
                //返回 returnStr = ""
            }
        } catch (Exception e) {
            log.info("Http请求出现异常:" + e);
            //返回 returnStr = ""
        } finally {
            responseClose(response);
        }
        return returnStr;
    }

    /**
     * 资源释放
     */
    private static void responseClose(CloseableHttpResponse response) {
        try {
            if (response != null) {
                response.close();
            }
        } catch (Exception e) {
            log.info("释放资源出现异常:" + e);
        }
    }
}